// pages/Goods/goodsOrder/index.js
var common = require("../../../../public.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: [],
    token: '',
    orderList: [],
    status: 0,
    not: true,
    have: false,
    pageNum: 1,
    active: 0,
    noMoreData: true,
    currentIndex: 0,
    isLoadingBusy: false,
    // type: 1,
    refreshing: false,

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.data.type = options.type?options.type:1;
    const that = this
    common.getLocalUserInfo(function (success, data) {
      console.log(data, "111111")
      if (success) {
        console.log(data, "111111")
        that.setData({
          userInfo: data.user,
          token: data.token,
          openid: data.openid,
        //   type: options.type
        }, function () {
          // 1为普通商品订单
          // if (options.type == 1) {
          that.reloadData()
          // }
        })
      }
    }, true)
  },
  // 查看物流
  Toexpress(e) {
    let { expressNumber, picPath, expressCompany } = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/packageB/pages/express/express?expressNumber=' + expressNumber +
        '&storeImage=' + picPath + '&expressCompany=' + expressCompany,
    })
  },
  // 删除按钮点击事件
  onDelete(e) {
    const orderId = e.currentTarget.dataset.item.orderId
    const that = this
    common.showAlertView('提示', '是否删除该订单？', function (res) {
      if (res) {
        that.submitDelete(orderId)
      }
    })
  },
  // 提交删除事件
  submitDelete(orderId) {
    const that = this
    common.post('/order/delete', {
      orderId,
      userId: that.data.userInfo.id,
      token: that.data.token
    },
      function (res) {
        if (res.status == 200) {
          common.showToast('删除成功！')
          that.reloadData()
        } else {
          common.showRequestErrMsg(res)
        }
      })
  },
  onChange(event) {
    const index = event.detail.name
    this.data.status = index
    this.reloadData(true)
  },

  toComment(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '/pages/comment/index?orderId=' + item.orderId,
    })
  },
  cancelOrder(e) { // 取消订单
    const that = this
    common.showAlertView('提示', '是否取消该订单', function (res) {
      if (res) {
        let orderId = e.currentTarget.dataset.item.orderId
        let tempJson = {
          userId: that.data.userInfo.id,
          token: that.data.token,
          orderId: orderId
        }
        common.post('/order/cancel', tempJson, function (res) {
          if (res.status === 200) {
            common.showToast('已取消订单')
            that.reloadData()
          } else {
            common.showRequestErrMsg(res)
          }
        })
      }
    })
  },
  payNow(e) {
    console.log("支付")
    const item = e.currentTarget.dataset.item
    const that = this
    const tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      orderId: item.orderId,
    //   openid: that.data.openid,
      xcxOpenid: that.data.openid,
    }
   // 自有支付  wxxcxPayForGoods
    common.wxPayRequest('/wxxcxPayForGoods', tempJson, function (res) {
        //  common.wxPayRequest('/wxxcxPayGoodsForChinaUms', tempJson, function (res) {

            if (res.status !== 200) {
                common.showRequestErrMsg(res)
            } else {
                    //微信支付
                    wx.requestPayment({
                    'timeStamp': res.data.timeStamp,
                    'nonceStr': res.data.nonceStr,
                    'package': res.data.package,
                    'signType': res.data.signType,
                    'paySign': res.data.paySign,
                    'success': function (res) {

                        that.reloadData()
                    },
                    'fail': function (res) {

                        if (res.errMsg === 'requestPayment:fail cancel') {
                        } else {
                        common.showToast(res.errMsg)
                        }
                    }
                    })
            }
    })
  },
  // 确认收货
  confirm(e) {
    const item = e.currentTarget.dataset.item
    const that = this
    const param = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      orderId: item.orderId
    }
    common.post('/order/confirm', param, function (res) {
      if (res.status === 200) {
        common.showToast('确认收货成功', 'success')
        that.reloadData()
      } else {
        common.showRequestErrMsg(res)
      }
    })
  },
  /**
   * 获取订单列表
   * @param {boolean} refresh 是否刷新列表数据
   */
  getOrderList(refresh = false) {
    if (this.data.isLoadingBusy === true) {
      return
    }
    if (refresh) {
      // 这里要区分是加载新的tab数据还是刷新数据
      // 加载新的tab数据不显示下拉刷新，下拉刷新才需要显示
      this.setData({
        noMoreData: false,
        isLoadingBusy: true,
        refreshing: true
      })
    } else {
      if (this.data.noMoreData === true) {
        return
      }
      this.setData({
        isLoadingBusy: true
      })
    }

    const pageNum = refresh ? 1 : this.data.pageNum + 1
    const that = this

    var url
    // if (that.data.type == 1) {
      console.log('商品订单楼')
      var tempJson = {
        userId: that.data.userInfo.id,
        status: that.data.status,
        token: that.data.token,
        pageSize: 10,
        pageNum
      }
      url = '/order/list'
    // } else {
    //   console.log('团购订单楼')
    //   var tempJson = {
    //     buyUserId: that.data.userInfo.id,
    //     status: that.data.status,
    //     token: that.data.token,
    //     pageNum,
    //     count: 10
    //   }
    //   url = '/crowdfundingOrder/getList'
    // }

    common.getJson(url, tempJson, function (res) {
      if (res.status == 200) {
        that.data.pageNum = pageNum
        let orderList = []
        if (res.data === null || res.data.length === 0) {
          that.setData({
            noMoreData: true
          })
        } else {
          for (var i = 0; i < res.data.length; i++) {
              var twoList = res.data[i].list;
              var totalNum = 0;
            for (var j = 0; j < twoList.length; j++) {
                totalNum =twoList[j].num + totalNum;
            }
            res.data[i].list[0].num = totalNum;
            orderList.push(res.data[i].list[0])
          }
          that.setData({
            orderList: refresh ? orderList : [...that.data.orderList, ...orderList]
          })
        }
      } else if (res.msg == '您还没有订单') {
        that.setData({
          noMoreData: true
        })
      } else {
        common.showRequestErrMsg(res)
      }
    }, function () {
      that.setData({
        isLoadingBusy: false
      })
      if (refresh) {
        that.setData({
          refreshing: false
        })
      }
    })
  },
  loadMore() {
    this.getOrderList()
  },
  /**
   * 加载tab页数据
   */
  reloadData() {
    this.setData({
      orderList: [],
    }, _ => {
      this.getOrderList(true)
    })
  },
  toDetail(e) {
    console.log(e, "eeeeeeeeeeeeeeeeeeeeeeeeeeee")

    const item = e.currentTarget.dataset.item
    this.shopInfo(item, 2)
    // wx.navigateTo({
    //   url: '../goodsOrderDetail/index?orderId=' + item.orderId
    // })
  },
  toStore(e) {
    // common.gotoStore(e.currentTarget.dataset.item)
    this.shopInfo(e.currentTarget.dataset.item, 1)
  },

  getOrderDes(num,item){
    var that = this;
    this.setData({
        isLoading: true
    })
    common.post('/order/getOrderDetail', {
            userId: that.data.userInfo.id,
            orderId: item.orderId,
            token: that.data.token
        },
        function (responseData) {
            if (responseData && responseData.status === 200) {
                console.log('idx----',responseData.data[0].status);
                if(responseData.data[0].status==5){
                    this.commonDealFunc(num,item);
                }else{
                    if (num == 1) {
                        console.log('22222');
                      common.gotoStore(item)
                    } else {
                        console.log('23333333333333333');
                      wx.navigateTo({
                        url: '../goodsOrderDetail/index?orderId=' + item.orderId
                      })
                    }
                }
            } else {
                common.showRequestErrMsg(responseData)
            }
        },
        function () {
            that.setData({
                isLoading: false
            })
        }
    )
},

  // 判断模板 industryType   行业类型  1通用行业 2餐饮行业  3家电行业
  shopInfo(item, num) {  // num为1进入门店，  num为2进入详情

    var that = this
    var tempJson = {
      storeId: item.storeId,
      // storeId:33,
      xpoint: this.data.lat,
      ypoint: this.data.lon,
      xcFlag: '0' //是否含有携程门票 0不含有
    }
    common.get('/store/mainPageInfo', tempJson, res => {
      that.setData({
        industryType: res.data.store.industryType
      }, () => {
          console.log('1111222',this.data.industryType);
        //   配送方式 1平台配送 2到店自提 3快递配送 4扫码点餐
          if(item.postType==4){
            if (num == 1) {
                wx.navigateTo({
                  url: `/packageC/pages/activeBei/activeBei?id=${item.storeId}&name=${item.storeName}`,
                })
              } else {
                console.log('status---',item.status);
                if (item.status == 1) {
                    console.log('item---',item.orderId);
    
                  wx.navigateTo({
                    url: '../goodsOrderDetail/index?orderId=' + item.orderId
                  })
    
                } else if (item.status == 6) {  //取已消
                  wx.navigateTo({
                    url: `/packageC/pages/takeoutCanselDetail/takeoutCanselDetail?orderId=${item.orderId}&name=${item.storeName}`,
                  })
                } else if (item.status == 2) {  //已完成
                  wx.navigateTo({
                    url: `/packageC/pages/takeoutComplete/takeoutComplete?orderId=${item.orderId}&name=${item.storeName}`,
                  })
                }else if (item.status == 5) {  //已完成
                    wx.navigateTo({
                      url: `/packageC/pages/takeoutComplete/takeoutComplete?orderId=${item.orderId}&name=${item.storeName}`,
                    })
                  }
              }
          }else{
            if (num == 1) {
                console.log('22222');
              common.gotoStore(item)
            } else {
                console.log('23333333333333333');
              wx.navigateTo({
                url: '../goodsOrderDetail/index?orderId=' + item.orderId
              })
            }
          }



    

      })
    })
  },


  // 判断模板 industryType   行业类型  1通用行业 2餐饮行业  3家电行业
//   shopInfo(item, num) {  // num为1进入门店，  num为2进入详情

//     var that = this
//     var tempJson = {
//       storeId: item.storeId,
//       // storeId:33,
//       xpoint: this.data.lat,
//       ypoint: this.data.lon,
//       xcFlag: '0' //是否含有携程门票 0不含有
//     }
//     common.get('/store/mainPageInfo', tempJson, res => {
//       that.setData({
//         industryType: res.data.store.industryType
//       }, () => {
//           console.log('1111222',this.data.industryType);
       
//         if (this.data.industryType == 2) {

//           // case 1:
//           //   statusName = '未支付'
//           //   break;
//           // case 2:
//           //   statusName = '已支付'
//           //   break;
//           // case 4:
//           //   statusName = '已发货'
//           //   break;
//           // case 5:
//           //   statusName = '交易完成'
//           //   break;
//           // case 6:
//           //   statusName = '交易关闭'
//           //   break;
//           // case 7:
//           //   statusName = '已退款'
//           if (num == 1) {
//             wx.navigateTo({
//               url: `/packageC/pages/activeBei/activeBei?id=${item.storeId}&name=${item.storeName}`,
//             })
//           } else {
//             console.log('status---',item.status);
//             if (item.status == 1) {
//                 console.log('item---',item.orderId);
//             //   //待支付
//             //   wx.navigateTo({
//             //     url: `/packageC/pages/takeoutTobepaid/takeoutTobepaid?orderId=${item.orderId}&name=${item.storeName}`,
//             //   })

//               wx.navigateTo({
//                 url: '../goodsOrderDetail/index?orderId=' + item.orderId
//               })

//             } else if (item.status == 6) {  //取已消
//               wx.navigateTo({
//                 url: `/packageC/pages/takeoutCanselDetail/takeoutCanselDetail?orderId=${item.orderId}&name=${item.storeName}`,
//               })
//             } else if (item.status == 2) {  //已完成
//               wx.navigateTo({
//                 url: `/packageC/pages/takeoutComplete/takeoutComplete?orderId=${item.orderId}&name=${item.storeName}`,
//               })
//             }else if (item.status == 5) {  //已完成
//                 wx.navigateTo({
//                   url: `/packageC/pages/takeoutComplete/takeoutComplete?orderId=${item.orderId}&name=${item.storeName}`,
//                 })
//               }
//           }
//           return
//         }




//         if (num == 1) {
//             console.log('22222');
//           common.gotoStore(item)
//         } else {
//             console.log('23333333333333333');
//           wx.navigateTo({
//             url: '../goodsOrderDetail/index?orderId=' + item.orderId
//           })
//         }

//       })
//     })
//   },
//   // 判断模板 industryType   行业类型  1通用行业 2餐饮行业  3家电行业
//   shopInfo(item, num) {  // num为1进入门店，  num为2进入详情
//     console.log('item-0--',item);
//     var that = this
//     var tempJson = {
//       storeId: item.storeId,
//       // storeId:33,
//       xpoint: this.data.lat,
//       ypoint: this.data.lon,
//       xcFlag: '0' //是否含有携程门票 0不含有
//     }
//     common.get('/store/mainPageInfo', tempJson, res => {
//       that.setData({
//         industryType: res.data.store.industryType
//       }, () => {
//           console.log('1111222',this.data.industryType);
       
//         if (this.data.industryType == 2) {

//             this.commonDealFunc(num,item);
//           return
//         }


//         this.getOrderDes(num,item);
        
        

//       })
//     })
//   },
// commonDealFunc(num,item){
//      // case 1:
//           //   statusName = '未支付'
//           //   break;
//           // case 2:
//           //   statusName = '已支付'
//           //   break;
//           // case 4:
//           //   statusName = '已发货'
//           //   break;
//           // case 5:
//           //   statusName = '交易完成'
//           //   break;
//           // case 6:
//           //   statusName = '交易关闭'
//           //   break;
//           // case 7:
//           //   statusName = '已退款'
//           if (num == 1) {
//             wx.navigateTo({
//               url: `/packageC/pages/activeBei/activeBei?id=${item.storeId}&name=${item.storeName}`,
//             })
//           } else {
//             console.log('status---',item.status);
//             if (item.status == 1) {
//                 console.log('item---',item.orderId);
//             //   //待支付
//             //   wx.navigateTo({
//             //     url: `/packageC/pages/takeoutTobepaid/takeoutTobepaid?orderId=${item.orderId}&name=${item.storeName}`,
//             //   })

//               wx.navigateTo({
//                 url: '../goodsOrderDetail/index?orderId=' + item.orderId
//               })

//             } else if (item.status == 6) {  //取已消
//               wx.navigateTo({
//                 url: `/packageC/pages/takeoutCanselDetail/takeoutCanselDetail?orderId=${item.orderId}&name=${item.storeName}`,
//               })
//             } else if (item.status == 2) {  //已完成
//               wx.navigateTo({
//                 url: `/packageC/pages/takeoutComplete/takeoutComplete?orderId=${item.orderId}&name=${item.storeName}`,
//               })
//             }else if (item.status == 5) {  //已完成
//                 wx.navigateTo({
//                   url: `/packageC/pages/takeoutComplete/takeoutComplete?orderId=${item.orderId}&name=${item.storeName}`,
//                 })
//               }
//           }
// }

})